//
//  PhotoAlbumCollectionViewCell.swift
//  EasePods
//
//  Created by 易先生 on 2024/5/22.
//

import UIKit
import Photos

class PhotoAlbumCollectionViewCell: CollectionViewCell {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func makeUI() {
        
        self.contentView.addSubview(albumImageView)
        
        albumImageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    public func bind(to asset: PHAsset,
                     isPreview: Bool = false) {
            
        var targetSize: CGSize = CGSize(width: (UIScreen.main.bounds.width-2)/3, height: (UIScreen.main.bounds.width-2)/3)
        if isPreview {
            self.albumImageView.contentMode = .scaleAspectFit
            targetSize = PHImageManagerMaximumSize
        } else {
            self.albumImageView.contentMode = .scaleAspectFill
        }
        
        let imageManager = PHImageManager.default()
        let requestOptions = PHImageRequestOptions()
        requestOptions.isSynchronous = false
        requestOptions.deliveryMode = .highQualityFormat
        
        imageManager.requestImage(for: asset, targetSize: targetSize, contentMode: .aspectFill, options: requestOptions) { image, info in
            if let image = image {
                self.albumImageView.image = image
            }
        }
        
    }
    
    public lazy var albumImageView: ImageView = {
        let imageView = ImageView()
        imageView.contentMode = .center
        imageView.backgroundColor = .black
        imageView.clipsToBounds = true
        return imageView
    }()
}
